﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppMVVM.WCFWebRoleService;
using AppMVVM.DataAccess;

namespace AppMVVM.Models
{
    public class UserData : INotifyPropertyChanged
    {
        private DataDistributorClient _dataDistributor;

        private UserInformation _userInfo;
        private Credentials _credentials;
        private ConnectionState _connectionStatus;

        public UserData(Credentials credentials)
        {
            _dataDistributor = DataDistributor.Instance;

            _credentials = credentials;
            _connectionStatus = ConnectionState.Disconnected;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public string UserId
        {
            get
            {
                if (_userInfo != null)
                    return _userInfo.Id;
                return null;
            }
        }

        public ConnectionState ConnectionStatus
        {
            get
            {
                return _connectionStatus;
            }
            private set
            {
                if (_connectionStatus != value)
                {
                    _connectionStatus = value;
                    OnPropertyChanged("ConnectionStatus");
                }
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public void Connect()
        {
            if (ConnectionStatus == ConnectionState.Disconnected)
            {
                ConnectionStatus = ConnectionState.Connecting;
                _userInfo = _dataDistributor.GetUser(_credentials.Account, _credentials.Password);
                if (_userInfo != null && _userInfo.Email != null)
                    ConnectionStatus = ConnectionState.Connected;
                else
                    ConnectionStatus = ConnectionState.Disconnected;
            }
        }

        public void Disconnect()
        {
            ConnectionStatus = ConnectionState.Disconnected;
        }

    }
}
